package lp.polimi.treefinder;

import java.util.Locale;

import lp.polimi.treefinder.utils.FilesUtils;

import android.app.Activity;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;
import com.google.android.gms.plus.PlusShare;

/** Displays the details about the selected leaf (species name, address and date) and shows two buttons to share on Facebook and Google+.
 * For enable the user to share on G+, we use the Google+ API: there is no any activity related to G+ in this project
 * (unlike the Facebook's one), as is is already available in the API.
 */
public class LeafDataFragment extends Fragment implements ConnectionCallbacks, OnConnectionFailedListener {
	
	protected static final String TAG = LeafInsightsActivity.class.getName();
	private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
	private ProgressDialog mConnectionProgressDialog;
	private PlusClient mPlusClient;
	private ConnectionResult mConnectionResult;
	
	public LeafDataFragment() {
		// Required empty public constructor
	}
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		//google+
		mPlusClient = new PlusClient.Builder(getActivity(), this, this)
		.setActions("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity")
		.setScopes("PLUS_LOGIN")  // Space separated list of scopes
		.build();
		// Progress bar to be displayed if the connection failure is not resolved.
		mConnectionProgressDialog = new ProgressDialog(getActivity());
		mConnectionProgressDialog.setMessage(getResources().getString(R.string.signing_in));

	}

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_leaf_data, container, false);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		TextView date = (TextView) getActivity().findViewById(R.id.date_tv);
		date.setText(getActivity().getIntent().getExtras().getString(XMLHandler.KEY_DATE));

		TextView address = (TextView) getActivity().findViewById(R.id.address_tv);
		String address_str = getActivity().getIntent().getExtras().getString(XMLHandler.KEY_ADDRESS);
		address.setText(address_str);

		TextView city = (TextView) getActivity().findViewById(R.id.city_tv);
		String city_str = getActivity().getIntent().getExtras().getString(XMLHandler.KEY_CITY);
		city.setText(city_str);

		TextView country = (TextView) getActivity().findViewById(R.id.country_tv);
		String country_str = getActivity().getIntent().getExtras().getString(XMLHandler.KEY_COUNTRY);
		country.setText(country_str);

		ImageView photo = (ImageView) getActivity().findViewById(R.id.leaf_image);
		photo.setImageBitmap(FilesUtils.retrieveLeafBitmap(getActivity(), getActivity().getIntent().getExtras().getString(XMLHandler.KEY_NAME), "png"));



		//google+
		ImageButton gplus = (ImageButton)getActivity().findViewById(R.id.gplus_button);
		gplus.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Uri selectedImage = FilesUtils.retrieveLeafUri(getActivity(), getActivity().getIntent().getExtras().getString(XMLHandler.KEY_NAME), "jpg");

				PlusShare.Builder share = new PlusShare.Builder(getActivity());
				share.setText(getActivity().getIntent().getExtras().getString(XMLHandler.KEY_NAME).toUpperCase(Locale.US)+"\n"+
						getResources().getString(R.string.shared_message)+"\n"+getResources().getString(R.string.app_url));
				share.addStream(selectedImage);
				share.setType("image/jpg");
				startActivityForResult(share.getIntent(), 1);
			}
		});

		//facebook
		ImageButton fb = (ImageButton)getActivity().findViewById(R.id.facebook_button);
		fb.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {	
				Intent i = new Intent(getActivity(), FacebookShareActivity.class);
				i.putExtras(getActivity().getIntent().getExtras());
				startActivity(i);
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		
		
		//google+
		if (requestCode == REQUEST_CODE_RESOLVE_ERR && resultCode == Activity.RESULT_OK) {
			mConnectionResult = null;
			mPlusClient.connect();
		}

		super.onActivityResult(requestCode, resultCode, data);
	}


	@Override
	public void onConnectionFailed(ConnectionResult result) {
		if (mConnectionProgressDialog.isShowing()) {
			// The user clicked the sign-in button already. Start to resolve
			// connection errors. Wait until onConnected() to dismiss the
			// connection dialog.
			if (result.hasResolution()) {
				try {
					result.startResolutionForResult(getActivity(), REQUEST_CODE_RESOLVE_ERR);
				} catch (SendIntentException e) {
					mPlusClient.connect();
				}
			}
		}
		mConnectionResult = result;
	}

	@Override
	public void onConnected(Bundle connectionHint) {
		// google+
		// We've resolved any connection errors.
		mConnectionProgressDialog.dismiss();
	}


	@Override
	public void onStart() {
		super.onStart();

		//google+
		mPlusClient.connect();
	}

	@Override
	public void onStop() {
		super.onStop();

		//google+
		mPlusClient.disconnect();
	}


	@Override
	public void onDisconnected() {
		Log.d("google+", "Disconnected.");
	}

}
